//
import * as qiniu from 'qiniu-js'

import {
  Loading
} from 'element-ui'
import { post } from '@/utils/request' // 全屏 dialog

const qiniuSpace = 'https://upqiniu.tx2.isart.me/'

function getQiNiuToken() {
  return new Promise((resolve, reject) => {
    post('api/global/getQiniuToken').then(ret => {
      resolve(ret.data)
    }).finally(()=>{

    })
  })
}

// 上传 普通文件
/*
    回调函数 返回值有三种类型
    false 处理的 七牛token 获取失败后的处理
    number 为上传过程中的进度 0-100
    string 为上传后的最终结果，网络路径
*/
function uploadNormalFile(file, callBack) {
  post('api/global/getQiniuToken').then(ret => {
    const token = ret.data
    // 获取文件后缀
    const file_suffix = file.name.substr(file.name.lastIndexOf('.'))

    const key = new Date().getTime() + Math.random().toString(36).slice(-8) + file_suffix
    const observable = qiniu.upload(file, key, token) // 返回一个实例
    var cb = {
      next(res) {
        var percent = res.total.percent
        callBack(percent)
      },
      complete(res) {
        const final_url = `${qiniuSpace}${res.key}`
        callBack(final_url)
      },
      error(err) {
        callBack(false)
      }
    }
    observable.subscribe(cb)
  }).catch(() => {
    callBack(false)
  })
}

// 上传 base 64 文件
function uploadBase64(data64) {
  return new Promise(async(resolve, reject) => {
    let qnToken = ''
    await axiosFun({}).then(ret => {
      qnToken = ret.ret
    })
    var url = 'https://up.qiniup.com' + window.btoa(new Date().getTime() + parseInt(Math.random() * 10))
    var xhr = new XMLHttpRequest()
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
        var back_json = JSON.parse(xhr.responseText)
        const imgUrl = `${qiniuSpace}${back_json.key}`
        resolve(imgUrl)
      }
    }
    xhr.open('POST', url, true)
    xhr.setRequestHeader('Content-Type', 'application/octet-stream')
    xhr.setRequestHeader('Authorization', `UpToken ${qnToken}`)
    xhr.send(data64)
  })
}
export {
  uploadNormalFile,
  getQiNiuToken,
  uploadBase64
}
